import React,{useState, useRef, useEffect, createRef} from 'react';
import { connect } from 'react-redux'

const Li = (props) => {
    const {data, dispatch} = props;
    const {id, done, txt} = data;
    const [edit, setEdit] = useState(false);
    const [inputVal, setInputVal] = useState(txt);

    const ref = createRef();

    useEffect(() => {
        if(edit){
            ref.current.select();
        }
    }, [edit])

    return (
        <li className={edit ? "editing" : ''}>
            <div className={"todo "+ (done?"done":"")}>
                <div className="display">
                    <input 
                        className="check" 
                        type="checkbox"
                        checked={done}
                        onChange={
                            ({target}) => {
                                dispatch({
                                    type: 'UPDATE_DONE',
                                    id,
                                    done: target.checked
                                })
                            }
                        }
                    />
                    <div 
                        className="todo-content"
                        onDoubleClick={() => {
                            setEdit(!edit);
                        }}
                    >{txt}</div>
                    <span 
                        className="todo-destroy"
                        onClick={()=>{
                            dispatch({
                                type: 'REMOVE',
                                id
                            })
                        }}
                    ></span>
                </div>
                <div className="edit">
                    <input 
                        className="todo-input" 
                        type="text"
                        ref={ref}
                        value={inputVal}
                        onChange={({target})=>{
                            setInputVal(target.value);
                        }}
                        onBlur={({target}) => {
                            setEdit(false)
                            if(inputVal.trim()){
                                dispatch({
                                    type: 'UPDATE_TXT',
                                    id,
                                    val: target.value
                                })
                            } else{
                                setInputVal(txt)
                            }
                        }}
                    />
                </div>
            </div>
        </li>
    )
}

export default connect((state, props) => {
    const {data} = props;
    return {
        data: {...data}
    }
})(Li);
